package cn.wgspring.game.sevenwondersserver;

import jakarta.websocket.Session;
import org.json.JSONObject;

import java.io.IOException;
import java.util.concurrent.ConcurrentLinkedQueue;

public class Room {

    private final ConcurrentLinkedQueue<Session> players = new ConcurrentLinkedQueue<>();

    public Room() {
    }

    public int join(Session player) {
        players.add(player);
        return players.size();
    }

    public int remove(Session player) {
        players.remove(player);
        return players.size();
    }

    public int removeAllExcept(Session player) {
        players.forEach(p -> {
            if (p != player) {
                try {
                    p.close();
                } catch (IOException ignored) {
                }
                players.remove(p);
            }
        });
        return players.size();
    }

    public boolean roomIsEmpty() {
        return players.isEmpty();
    }

    public void onReceiveMessage(String msg) {
        // 无论如何先转发出去
        players.forEach(player -> sendRawMessage(player, msg));
    }

    public void broadcastSystemMessage(String message) {
        String msg = buildMsg("System", message);
        players.forEach(player -> sendRawMessage(player, msg));
    }

    public static String buildMsg(String from, String text) {
        return buildMsg(from, text, "{}");
    }

    public static String buildMsg(String from, String text, String extra) {
        JSONObject obj = new JSONObject();
        obj.put("from", from);
        obj.put("text", text);
        obj.put("extra", extra);
        return obj.toString();
    }

    private void sendRawMessage(Session player, String text) {
        try {
            player.getBasicRemote().sendText(text);
        } catch (Exception ignored) {
        }
    }
}
